package com.spic.business.train.plan.domain;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;

/**
 * CustomConverter 将String转换成int,如果为空则转成0
 *
 * @author xuxiaochang@chinasofi.com
 * @date 2022/7/21
 */
public class CustomConverter implements Converter<String>
{
    @Override
    public Class<?> supportJavaTypeKey()
    {
        return Converter.super.supportJavaTypeKey();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey()
    {
        return Converter.super.supportExcelTypeKey();
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception
    {
        return Converter.super.convertToJavaData(cellData, contentProperty, globalConfiguration);
    }

    @Override
    public String convertToJavaData(ReadConverterContext<?> context) throws Exception
    {
        BigDecimal value = context.getReadCellData().getNumberValue();
        if (value == null)
        {
            value = new BigDecimal(0);
        }
        return value.toString();
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception
    {
        return Converter.super.convertToExcelData(value, contentProperty, globalConfiguration);
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) throws Exception
    {
        return new WriteCellData<>(context.getValue());
    }
}
